package site.addzero.cli.autoinit.mac

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.koin.core.annotation.Single
import site.addzero.cli.platform.PlatformTools
import site.addzero.cli.platform.runCmd
import site.addzero.cli.setting.SettingContext
import site.addzero.task.InitTask
import java.io.File
import java.security.MessageDigest

/**
 * 已执行的优化项记录
 */
@Serializable
data class ExecutedOptimization(
    val hash: String,
    val command: String,
    val timestamp: Long
)

/**
 * macOS 系统优化状态数据类
 */
@Serializable
data class MacOptimizationStatus(
    val executedOptimizations: Set<ExecutedOptimization> = emptySet()
)

/**
 * macOS 系统自动初始化类
 * 负责配置 macOS 系统参数，提升使用体验
 */
@Single
class AutoInitMac : InitTask {

    override val support: Boolean = PlatformTools.isMac()

    override suspend fun asynctask(): Boolean {
        // 检查是否为 Mac 系统
        if (!PlatformTools.isMac()) return false

        // 显示推荐的优化项并逐行确认
        showAndConfirmOptimizations()
        return true
    }

    /**
     * 初始化 macOS 系统配置
     */
    private fun initializeMac() {
        // 只在支持的平台上执行
        if (!support) return

        // 显示推荐的优化项并逐行确认
        showAndConfirmOptimizations()
    }

    /**
     * 计算命令的哈希值
     */
    private fun calculateHash(command: String): String {
        val digest = MessageDigest.getInstance("SHA-256")
        val hashBytes = digest.digest(command.toByteArray())
        return hashBytes.joinToString("") { "%02x".format(it) }
    }

    /**
     * 获取已执行的优化项列表
     */
    private fun getExecutedOptimizations(): Set<ExecutedOptimization> {
        val statusFile = File(SettingContext.MAC_OPTIMIZATION_STATUS_FILE)
        if (statusFile.exists()) {
            try {
                val content = PlatformTools.readFile(SettingContext.MAC_OPTIMIZATION_STATUS_FILE)
                val status = Json.decodeFromString<MacOptimizationStatus>(content)
                return status.executedOptimizations
            } catch (e: Exception) {
                println("读取macOS优化状态文件失败: ${e.message}")
                return emptySet()
            }
        }
        return emptySet()
    }

    /**
     * 保存已执行的优化项
     */
    private fun saveExecutedOptimization(command: String) {
        try {
            // 确保目录存在
            val statusDir = File(SettingContext.STATUS_DIR)
            if (!statusDir.exists()) {
                statusDir.mkdirs()
            }

            // 获取现有的优化项
            val existingOptimizations = getExecutedOptimizations().toMutableSet()

            // 添加新的优化项
            val hash = calculateHash(command)
            val executedOptimization = ExecutedOptimization(hash, command, System.currentTimeMillis())
            existingOptimizations.add(executedOptimization)

            // 保存状态
            val status = MacOptimizationStatus(existingOptimizations)
            val content = Json.encodeToString(status)
            PlatformTools.writeFile(SettingContext.MAC_OPTIMIZATION_STATUS_FILE, content)
        } catch (e: Exception) {
            println("保存macOS优化状态失败: ${e.message}")
        }
    }

    /**
     * 显示推荐的 macOS 优化项并逐行确认
     */
    private fun showAndConfirmOptimizations() {
        // 获取已执行的优化项
        val executedOptimizations = getExecutedOptimizations()
        val executedHashes = executedOptimizations.map { it.hash }.toSet()

        println("\n推荐的 macOS 系统优化项:")
        println("========================================")

        // 使用Map关联命令和描述
        val optimizationMap = mapOf(
            "pwpolicy -clearaccountpolicies" to "设置密码策略",
            "sudo nvram SystemAudioVolume=\" \"" to "关闭开机声音",
            "defaults write com.apple.menuextra.battery ShowPercent -bool true" to "电池显示百分比",
            "defaults write NSGlobalDomain KeyRepeat -int 3" to "设置键盘按键重复延迟",
            "defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false" to "禁止自动拼写纠正",
            "defaults write com.apple.finder ShowStatusBar -bool true" to "Finder 显示状态栏",
            "defaults write com.apple.finder ShowPathbar -bool true" to "Finder 显示地址栏",
            "defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true" to "禁止在网络驱动器上生成 .DS_Store 文件",
            "sudo spctl --master-disable" to "开启所有来源",
            "defaults write com.apple.finder _FXShowPosixPathInTitle -bool YES" to "减弱Finder动态效果",
            "defaults write com.apple.dock workspaces-swoosh-animation-off -bool YES" to "减弱Dock动态效果"
        )

        // 过滤掉已执行的优化项
        val filteredOptimizations = optimizationMap.filter { (command, _) ->
            val hash = calculateHash(command)
            !executedHashes.contains(hash)
        }

        if (filteredOptimizations.isEmpty()) {
            println("所有优化项均已执行，无需重复执行")
            return
        }

        // 显示过滤后的优化项
        filteredOptimizations.values.forEachIndexed { index, description ->
            println("${index + 1}. $description")
        }

        println("========================================")
        println("按回车键逐项确认，输入 'a' 接受所有优化项，或按 'q' 退出:")

        var acceptAll = false
        for ((index, entry) in filteredOptimizations.entries.withIndex()) {
            val (command, description) = entry
            if (!acceptAll) {
                print("应用优化项 ${index + 1} [$description] (按回车确认,输入 'a' 接受全部优化项不再提示,输入 'q' 退出,输入's' 跳过): ")
                val input = PlatformTools.readLine()?.lowercase()

                when (input) {
                    "a" -> acceptAll = true
                    "s" -> continue
                    "q" -> return
                    else -> {
                        // 默认接受，继续执行
                    }
                }
            } else {
                // 如果acceptAll为true，自动执行并提示
                println("自动应用优化项 ${index + 1} [$description]")
            }

            // 执行命令
            println("执行: $command")
            command.runCmd()

            // 保存执行记录
            saveExecutedOptimization(command)
        }

        // 重启相关服务使配置生效
        "killall Finder".runCmd()
        "killall Dock".runCmd()

        println("macOS 系统初始化完成")
    }
}
